package cn.lili.controller.permission;

import cn.lili.common.aop.annotation.DemoSite;
import cn.lili.common.enums.ResultCode;
import cn.lili.common.enums.ResultUtil;
import cn.lili.common.exception.ServiceException;
import cn.lili.common.security.context.UserContext;
import cn.lili.common.security.enums.UserEnums;
import cn.lili.common.vo.PageVO;
import cn.lili.common.vo.ResultMessage;
import cn.lili.modules.member.entity.dos.Member;
import cn.lili.modules.member.entity.dos.Partner;
import cn.lili.modules.member.entity.vo.MemberSearchVO;
import cn.lili.modules.member.entity.vo.MemberVO;
import cn.lili.modules.member.mapper.PartnerMapper;
import cn.lili.modules.member.service.EextensionService;
import cn.lili.modules.member.service.MemberService;
import cn.lili.modules.member.service.PartnerService;
import cn.lili.modules.permission.entity.dos.AdminUser;
import cn.lili.modules.permission.entity.dos.Audit;
import cn.lili.modules.permission.entity.dos.Role;
import cn.lili.modules.permission.service.AdminUserService;
import cn.lili.modules.permission.service.AuditService;
import cn.lili.modules.permission.service.RoleService;
import cn.lili.modules.store.service.StoreService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import static cn.lili.common.enums.ResultCode.AUDIT_TYPE_ERROR;

/**
 * create by yudan on 2022/2/10
 */
@RestController
@Api(tags = "代理商接口")
@RequestMapping("/manager/agent")
public class AgentController {

	@Autowired
	private AdminUserService adminUserService;
	@Autowired
	private AuditService auditService;

	@Autowired
	private MemberService memberService;
	@Autowired
	private RoleService roleService;
	@Autowired
	private PartnerMapper partnerMapper;
	@Autowired
	private EextensionService eextensionService;
	@Autowired
	private PartnerService partnerService;

	@ApiOperation(value = "代理商分页列表")
	@GetMapping
	public ResultMessage<IPage<MemberVO>> getByPage(MemberSearchVO memberSearchVO, PageVO page) {
		return ResultUtil.data(memberService.updateAgent(memberSearchVO, page));
	}

	@ApiOperation(value = "审核申请")
	@PutMapping(value = "/audit")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "会员ID", required = true, dataType = "String", allowMultiple = true, paramType = "query"),
			@ApiImplicitParam(name = "auditState", required = true, dataType = "String", paramType = "query"),
			@ApiImplicitParam(name = "auditRemark", value = "驳回理由", required = true, dataType = "String", paramType = "query")})
	public ResultMessage<Object> audit(@Valid String id, String auditState, String auditRemark) {
		if (!"PASS".equals(auditState) && !"REFUSED".equals(auditState)) {
			return ResultUtil.error(AUDIT_TYPE_ERROR);
		}
		memberService.auditPartner(id, auditState, auditRemark);
		if ("PASS".equals(auditState)) {
			// 审核通过后将其他身份设置deleflage设置为1
			QueryWrapper<Partner> queryWrapperOther = new QueryWrapper<Partner>().eq("delete_flag", false)
					.notIn("partner_type", 4).eq("member_id", id);
			List<Partner> partnerListOther = partnerMapper.selectList(queryWrapperOther);
			if (partnerListOther.size() > 0) {
				for (Partner partner : partnerListOther) {
					partner.setDeleteFlag(true);
					partnerService.updateById(partner);
				}
			}

			AdminUser adminUser = new AdminUser();
			Member member = memberService.getById(id);
			member.setPromotionCode(eextensionService.getExtension());
			adminUser.setMobile(member.getMobile());
			adminUser.setAvatar(member.getFace());
			adminUser.setUsername(member.getUsername());
			adminUser.setNickName(member.getNickName());
			adminUser.setIsSuper(false);
			adminUser.setPassword(member.getPassword());
			adminUser.setStatus(true);
			adminUser.setPromotionCode(member.getPromotionCode());

			QueryWrapper<Partner> queryWrapper = new QueryWrapper<Partner>().eq("delete_flag", false)
					.eq("partner_type", 4).eq("member_id", id);
			List<Partner> partnerList = partnerMapper.selectList(queryWrapper);
			if (partnerList.size() != 1) {
				throw new ServiceException(ResultCode.USER_PARTNER_ERROR);
			}
			Partner partner = partnerList.get(0);
			adminUser.setRegion(partner.getRegion());
			adminUser.setRegionId(partner.getRegionId());

			QueryWrapper<Role> wrapper = Wrappers.query();
			wrapper.eq("name", UserEnums.AGENT.getRole());
			Role role = roleService.getOne(wrapper);
			List<String> list = new ArrayList<>();
			list.add(role.getId());
			adminUser.setRoleIds(role.getId());
			adminUserService.save(adminUser);
			adminUserService.updateRole(adminUser.getId(), list);
		}
		return ResultUtil.success();
	}

	@ApiOperation(value = "修改会员基本信息")
	@PutMapping
	@DemoSite
	public ResultMessage<Object> update(@Valid AdminUser adminUser) {
		return ResultUtil.data(adminUserService.updateAdminUserRegion(adminUser));
	}

	@ApiOperation(value = "删除代理商")
	@ApiImplicitParam(name = "id", value = "代理商ID", required = true, allowMultiple = true, dataType = "String", paramType = "path")
	@DeleteMapping(value = "/delByIds/{id}")
	public ResultMessage<Object> delAllByIds(@NotNull(message = "代理商ID不能为空") @PathVariable("id") String id) {
		Member member = memberService.getById(id);
		if (null != member) {
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("mobile", member.getMobile());
			AdminUser one = adminUserService.getOne(queryWrapper);
			if (null != one) {
				auditService.deleteByUserId(one.getId(), 1);
			}
			partnerMapper.updateByMemberId(id);
		}
		return ResultUtil.success();
	}

	@ApiOperation(value = "修改会员状态,开启关闭会员")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "代理商ID", required = true, dataType = "String", allowMultiple = true, paramType = "query"),
			@ApiImplicitParam(name = "disabled", required = true, dataType = "boolean", paramType = "query")})
	@RequestMapping("/updateStatus")
	@DemoSite
	public ResultMessage<Object> updateStatus(@RequestParam String id, @RequestParam Boolean status) {
		Member member = memberService.getById(id);
		if (null != member) {
			QueryWrapper queryWrapper = new QueryWrapper();
			queryWrapper.eq("mobile", member.getMobile());
			AdminUser one = adminUserService.getOne(queryWrapper);
			if (null != one) {
				adminUserService.updateStatus(one.getId(), status);
			}
		}
		return ResultUtil.success();
	}

}
